package com.utils.protobuffer;

import com.google.protobuf.InvalidProtocolBufferException;
import com.googlecode.protobuf.format.JsonFormat;
import com.googlecode.protobuf.format.JsonFormat.ParseException;
import com.utils.protobuffer.personProto.Person;
/**
 * 下载 protoc-2.5.0-win32.zip
 * cmd: protoc.exe --java_out=./ w.proto
 * @author liangrui
 *
 */
public class Main {
	
	public static void main(String[] args) throws Exception {
//		main2(null);
//		main3(null);
		main4(null);
	}
	
	//序列化  /返序列化
	public static void main2(String[] args) throws InvalidProtocolBufferException {
		//序列化
		Person.Builder builder=Person.newBuilder();
		builder.setId(10);
		builder.setEmail("fx@qq.com");
        builder.setName("haha");
		Person info=builder.build();  
	    byte[] result=info.toByteArray() ; 
	    //返序列化
	    Person msg = Person.parseFrom(result);  
        System.out.println(msg); 
       
	}
	
	//protobuf转json
	public static void main3(String[] args) throws InvalidProtocolBufferException {
		
		//序列化
		Person.Builder builder=Person.newBuilder();
		builder.setId(10);
		builder.setEmail("fx@qq.com");
        builder.setName("haha");
		Person info=builder.build();  
	    byte[] result=info.toByteArray() ;  
	    
	
	    //返序列化
	    Person hello = Person.parseFrom(result);  
        System.out.println(hello); 
        
		String jsonFormat =JsonFormat.printToString(hello);
		System.out.println(jsonFormat);
		
	}
	
	//josn转protobuf
	public static void main4(String[] args) throws ParseException {
		Person.Builder builder =Person.newBuilder();
		String jsonFormat = "{id:11,email:'xxx@qq.com',name:'hh'}";
		JsonFormat.merge(jsonFormat, builder);
		
		System.out.println(builder.build());
		
	}
 
}
